package com.dctp.common.manager;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ShardManager {

    private static final Logger logger = LoggerFactory.getLogger(ShardManager.class);
    private static Set<Integer> myShards = new HashSet<>();

    // 启动时调用，传入当前 serverId（可以是 IP、主机名、或配置文件里的名字）
    public static void loadShards(String serverId) {
        List<Record> shards = Db.find("SELECT shard_id FROM dctp_server_shard_mapping WHERE server_id = ?", serverId);
        myShards = shards.stream()
                .map(r -> r.getInt("shard_id"))
                .collect(Collectors.toSet());
        logger.info("serverId ：{}，分片：{}", serverId, JSON.toJSON(myShards));
    }

    public static Set<Integer> getMyShards() {
        return myShards;
    }


    public static String getWsDomainByUserId(long userId) {

        Prop p = PropKit.use("project.properties");
        String env = p.get("env","prod");
        if ("prod".equals(env)) {
            int shard = (int) (userId % 16);
            if (shard <= 7) return "wss1.dctptrader.com";
            else return "wss2.dctptrader.com";
        }else {
            logger.info("测试环境，返回：traderder.com");
            return "traderder.com";
        }
    }

    public static String buildShardInClause() {
        return String.join(",", Collections.nCopies(myShards.size(), "?"));
    }
}
